package orm

import (
	"fmt"
	"gitee.com/whilew/cream/pkg/basic_component/conf"
	"gitee.com/whilew/cream/pkg/basic_component/log"
	"gorm.io/gorm"
)

var (
	DSN string
	// 最大活动连接数
	MaxOpenConns int
	// 最大空闲连接数
	MaxIdleConns int
)
var defaultDb *gorm.DB

func Initialize() (err error) {
	fmt.Println("开始初始化 orm ...")
	//语法https://www.kancloud.cn/sliver_horn/gorm/1861155
	DSN = conf.GetStringd("orm.dsn", DSN)
	if DSN == "" {
		fmt.Println("[Warn] DSN is empty skip initialize orm")
		return nil
	}
	// 解析dsn
	dialector, err := ParseOrmDsn(DSN)
	if err != nil {
		return err
	}
	defaultDb, err = gorm.Open(dialector, &gorm.Config{
		Logger: &ormLoger{
			Loger:         log.WithModule("orm").Clone(),
			is_need_trace: conf.GetBoold("orm.is_need_trace", false),
		},
	})
	if err != nil {
		return err
	}
	db, err := defaultDb.DB()
	if err != nil {
		return err
	}
	db.SetMaxOpenConns(conf.GetIntd("orm.conns.open.max", 50))
	db.SetMaxIdleConns(conf.GetIntd("orm.conns.idle.max", 50))
	// 自动映射表
	auto_migrate_model(defaultDb)
	return nil
}

func GetDB() *gorm.DB {
	if defaultDb != nil {
		return defaultDb
	}
	panic("please init db first")
}
